/*
 * $Id: JDatabaseTreePane.java 24 2009-03-31 23:40:10Z aaron.day $
 */
package org.crazydays.gameplan.data.swing.tree;


import java.io.File;

import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

import org.crazydays.gameplan.data.Database;
import org.crazydays.gameplan.map.IGameMap;

/**
 * JDatabaseTreePane
 */
public class JDatabaseTreePane
        extends JScrollPane
{
	/** serial version uid */
	public final static long serialVersionUID =
	        "$Id: JDatabaseTreePane.java 24 2009-03-31 23:40:10Z aaron.day $"
	                .hashCode();

	/** database */
	protected Database database;

	/** root */
	protected DefaultMutableTreeNode root;

	/** model */
	protected DefaultTreeModel model;

	/** tree */
	protected JTree tree;

	/**
	 * JDatabaseTreePanel constructor.
	 * 
	 * @param database Database
	 */
	public JDatabaseTreePane(Database database)
	{
		super(VERTICAL_SCROLLBAR_AS_NEEDED,
		        HORIZONTAL_SCROLLBAR_AS_NEEDED);

		setDatabase(database);
		initialize();
	}

	/**
	 * Initialize the panel.
	 */
	protected void initialize()
	{
		initializeTree();
	}

	/**
	 * Initialize tree.
	 */
	protected void initializeTree()
	{
		// model
		model = new DefaultTreeModel(getRoot());

		// create model and tree
		tree = new JTree(model);

		setViewportView(tree);
	}

	/**
	 * Get root tree node.
	 * 
	 * @return Root node
	 */
	protected DefaultMutableTreeNode getRoot()
	{
		if (root == null) {
			File file = getDatabase().getFile();
			if (file == null) {
				root =
				        new DefaultMutableTreeNode("Unsaved",
				                true);
			} else {
				root =
				        new DefaultMutableTreeNode(file
				                .getName().replaceAll(
				                        "\\..*?$", ""), true);
			}
		}

		return root;
	}

	/**
	 * Set database.
	 * 
	 * @param database Database
	 */
	public void setDatabase(Database database)
	{
		this.database = database;
	}

	/**
	 * Get database.
	 * 
	 * @return Database
	 */
	public Database getDatabase()
	{
		return database;
	}

	/**
	 * Add tree selection listener.
	 * 
	 * @param listener Listener
	 */
	public void addTreeSelectionListener(TreeSelectionListener listener)
	{
		if (tree == null) {
			throw new IllegalStateException("tree == null");
		}

		tree.addTreeSelectionListener(listener);
	}

	/**
	 * Add game map to tree.
	 * 
	 * @param gameMap Game map
	 */
	public void addGameMap(IGameMap gameMap)
	{
		if (gameMap == null) {
			throw new IllegalArgumentException("gameMap == null");
		}

		MutableTreeNode child =
		        new DefaultMutableTreeNode(gameMap.getName());

		getRoot().add(child);
		model.nodeStructureChanged(getRoot());
	}
}
